import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from "react";
import { Chart } from "@antv/g2";
import { copywriting_collection } from "../../utils/chartUtils";
import dayjs from "dayjs";
import isToday from 'dayjs/plugin/isToday';
dayjs.extend(isToday)

const LineChart = forwardRef(({
  chartData,
  meter,
}, ref) => {

  const charContainerRef = useRef(null);
  const charRef = useRef(null);

  const celt = useMemo(() => copywriting_collection(meter, chartData), [meter, chartData]);

  const initChart = (options) => {
    const chart = new Chart(options);

    // chart
    //   .data([
    //     { year: '1991', value: 3 },
    //     { year: '1992', value: 4 },
    //     { year: '1993', value: 3.5 },
    //     { year: '1994', value: 5 },
    //     { year: '1995', value: 4.9 },
    //     { year: '1996', value: 6 },
    //     { year: '1997', value: 7 },
    //     { year: '1998', value: 9 },
    //     { year: '1999', value: 13 },
    //   ])
    //   .encode('x', 'year')
    //   .encode('y', 'value')
    //   .scale('x', {
    //     range: [0, 1],
    //   })
    //   .scale('y', {
    //     domainMin: 0,
    //     nice: true,
    //   });

    // chart.line().label({
    //   text: 'value',
    //   style: {
    //     dx: -10,
    //     dy: -12,
    //   },
    // });

    chart
      .data([])
      .encode('x', {
        type: 'transform',
        value: (it) => dayjs.unix(it.time).format('YYYY-MM-DD HH:mm'),
      })
      .encode('y', {
        type: 'transform',
        value: (it) => parseFloat(it.body),
      })
      .scale('x', {
        range: [0, 1],
        nice: true,
      })
      .scale('y', {
        domainMin: 0,
        range: [1, 0],
        domain: celt.yScaleDomain,
        tickCount: 5,
        nice: true,
      })
      .axis('x', {
        title: '时间日期',
        titleSpacing: 0,
        labelFormatter: (d) => dayjs(d).format('HH:mm'),
        line: true,
        arrow: true,
      })
      .axis('y', {
        title: celt.yAxisLabel,
        titleSpacing: 0,
        titleFill: 'red',
        titleFontSize: 16,
        line: true,
        arrow: true,
        lineArrowOffset: 15,
        tick: true,
        label: true,
        labelFormatter: (d) => d,
        gridLineDash: null,
        gridStroke: 'red',
        gridStrokeWidth: 5,
        gridAreaFill: '#eee',
      })
      .transform({
        type: 'sample',
        thresholds: 200,
        strategy: 'max',
      })

    chart
      .line({
        connect: true,
        connectStroke: 'red',
        lineWidth: 20,
      })
      .label({
        text: 'body',
        formatter: (text) => `${parseFloat(text)?.toString()}${celt.yAxisUnit}`,
        style: {
          dx: -10,
          dy: -12,
        },
        transform: [{ type: 'overlapDodgeY' }],
      })
      .tooltip({
        title: (it) => dayjs.unix(it.time).format('YYYY-MM-DD HH-mm'),
        items: [{
          channel: 'y',
          name: celt.yToolTipName,
          valueFormatter: (text) => `${parseFloat(text)?.toString()}${celt.yAxisUnit}`,

        }]
      })
      .style('connect', true)
      .style('connectStroke', 'red')

    chart
      .point()
      .style('fill', 'white')
      .tooltip(false)

    chart.render()

    return chart
  }


  const changeChartData = (newData) => {
    if (charRef.current) {
      if (newData?.length) {
        charRef.current?.scale('y', {
          domainMin: 0,
          range: [1, 0],
          domain: celt.yScaleDomain,
          tickCount: 5,
          nice: true,
        })
      } else {
        charRef.current?.scale('y', {
          domain: [0, 100],
        })
      }
    }
    charRef.current?.changeData(newData);
  }

  useEffect(() => {
    if (charContainerRef.current && !charRef.current) {
      charRef.current = initChart({
        container: charContainerRef.current,
        autoFit: true,
        paddingTop: 10,
      })
    }

    if (charRef.current) {
      changeChartData(chartData)
    }

    return () => {
      if (charRef.current) {
        charRef.current?.destroy();
        charRef.current = null;
      }
    }
  }, [chartData])

  useImperativeHandle(ref, () => ({
    changeChartData,
  }))

  return (
    <div
      ref={charContainerRef}
    />
  )
})

export default LineChart
